<template>
  <div class="code-manage">
    <div class="page-header">
      <h2>代码管理</h2>
      <a-button type="primary" @click="showAddModal">
        <template #icon>
          <PlusOutlined />
        </template>
        新增代码
      </a-button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <a-form layout="inline" :model="searchForm">
        <a-form-item label="标题">
          <a-input v-model:value="searchForm.title" placeholder="请输入标题" />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleSearch">搜索</a-button>
          <a-button style="margin-left: 8px" @click="handleReset">重置</a-button>
        </a-form-item>
      </a-form>
    </div>

    <!-- 表格 -->
    <a-table
      :columns="columns"
      :data-source="dataSource"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
      row-key="id"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'tags'">
          <a-tag v-for="tag in parseTags(record.tags)" :key="tag" color="blue">
            {{ tag }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'content'">
          <div class="content-preview">{{ record.content.substring(0, 50) }}...</div>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button type="link" size="small" @click="showEditModal(record)">编辑</a-button>
            <a-popconfirm title="确定删除吗？" @confirm="handleDelete(record.id)">
              <a-button type="link" danger size="small">删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 新增/编辑弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      width="900px"
      :bodyStyle="{ maxHeight: '70vh', overflowY: 'auto' }"
    >
      <a-form :model="formState" :rules="rules" ref="formRef" :label-col="{ span: 4 }">
        <a-form-item label="标题" name="title">
          <a-input v-model:value="formState.title" placeholder="请输入标题" />
        </a-form-item>
        <a-form-item label="标签" name="tags">
          <a-select
            v-model:value="formState.tagList"
            mode="tags"
            placeholder="请选择已有标签或输入新标签，按回车添加"
            style="width: 100%"
            :options="allTags.map(tag => ({ label: tag.name, value: tag.name }))"
          />
        </a-form-item>
        <a-form-item label="内容" name="content">
          <MdEditor v-model="formState.content" :theme="'dark'" :previewTheme="'github'" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { pageCode, addCode, updateCode, deleteCode } from '@/api/code'
import { pageTag } from '@/api/tag'
import type { CodeVO, TagVO } from '@/types/api'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { MdEditor } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
import dayjs from 'dayjs'

// 搜索表单
const searchForm = reactive({
  title: undefined,
})

// 表格列定义
const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 100 },
  { title: '标题', dataIndex: 'title', key: 'title', width: 200 },
  { title: '内容', dataIndex: 'content', key: 'content', width: 250 },
  { title: '标签', dataIndex: 'tags', key: 'tags', width: 200 },
  { title: '查看次数', dataIndex: 'viewCount', key: 'viewCount', width: 100 },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 180,
    customRender: ({ text }: any) => dayjs(text).format('YYYY-MM-DD HH:mm'),
  },
  { title: '操作', key: 'action', width: 150, fixed: 'right' },
]

const dataSource = ref<CodeVO[]>([])
const allTags = ref<TagVO[]>([])
const loading = ref(false)
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total: number) => `共 ${total} 条`,
})

// 弹窗相关
const modalVisible = ref(false)
const modalTitle = ref('新增代码')
const isEdit = ref(false)
const formRef = ref()
const formState = reactive({
  id: undefined as string | undefined,
  title: '',
  content: '',
  tagList: [] as string[],
})

const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
}

// 解析标签
const parseTags = (tags?: string) => {
  if (!tags) return []
  try {
    return JSON.parse(tags)
  } catch {
    return []
  }
}

// 获取代码列表
const fetchCodeList = async () => {
  loading.value = true
  try {
    const res = await pageCode({
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...searchForm,
    })
    dataSource.value = res.data.list
    pagination.total = parseInt(res.data.total)
  } catch (error) {
    console.error('获取代码列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取所有标签（用于标签选择）
const fetchAllTags = async () => {
  try {
    const res = await pageTag({
      pageNo: 1,
      pageSize: 100, // 后端限制最大100
    })
    allTags.value = res.data.list
  } catch (error) {
    console.error('获取所有标签失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchCodeList()
}

// 重置
const handleReset = () => {
  searchForm.title = undefined
  pagination.current = 1
  fetchCodeList()
}

// 表格变化
const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchCodeList()
}

// 显示新增弹窗
const showAddModal = () => {
  modalTitle.value = '新增代码'
  isEdit.value = false
  resetForm()
  fetchAllTags() // 打开弹窗时加载所有标签
  modalVisible.value = true
}

// 显示编辑弹窗
const showEditModal = (record: CodeVO) => {
  modalTitle.value = '编辑代码'
  isEdit.value = true
  formState.id = record.id
  formState.title = record.title
  formState.content = record.content
  formState.tagList = parseTags(record.tags)
  fetchAllTags() // 打开弹窗时加载所有标签
  modalVisible.value = true
}

// 弹窗确定
const handleModalOk = async () => {
  try {
    await formRef.value.validate()
    const data = {
      ...formState,
      tags: JSON.stringify(formState.tagList),
    }
    if (isEdit.value) {
      await updateCode(data as any)
      message.success('编辑成功')
    } else {
      await addCode(data as any)
      message.success('新增成功')
    }
    modalVisible.value = false
    fetchCodeList()
  } catch (error) {
    console.error('操作失败:', error)
  }
}

// 弹窗取消
const handleModalCancel = () => {
  resetForm()
}

// 重置表单
const resetForm = () => {
  formState.id = undefined
  formState.title = ''
  formState.content = ''
  formState.tagList = []
  formRef.value?.resetFields()
}

// 删除
const handleDelete = async (id: string) => {
  try {
    await deleteCode({ id })
    message.success('删除成功')
    fetchCodeList()
  } catch (error) {
    console.error('删除失败:', error)
  }
}

onMounted(() => {
  fetchCodeList()
})
</script>

<style scoped>
.code-manage {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  color: #4a9eff;
  font-size: 24px;
}

.search-bar {
  margin-bottom: 24px;
  padding: 16px;
  background: rgba(26, 31, 58, 0.5);
  border-radius: 8px;
}

.content-preview {
  max-width: 250px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* Markdown 编辑器深色主题 */
:deep(.md-editor) {
  background: #0a0e27 !important;
  color: #e0e0e0 !important;
}

:deep(.md-editor-toolbar) {
  background: #1a1f3a !important;
  border-color: #3d4466 !important;
}

:deep(.md-editor-input-wrapper) {
  background: #0a0e27 !important;
}

:deep(.md-editor-input) {
  color: #e0e0e0 !important;
  caret-color: #4a9eff !important; /* 设置光标颜色为亮蓝色 */
}

:deep(.md-editor-preview) {
  background: #0a0e27 !important;
  color: #e0e0e0 !important;
}
</style>

